<!DOCTYPE html>
<html lang="zh-CN">
    <!-- title -->


    

<!-- keywords -->



<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="author" content="Lolipop">
    <meta name="renderer" content="webkit">
    <meta name="copyright" content="Lolipop">
    
        <meta name="keywords" content="Lolipop,frontend,full-stack,前端,全栈">
    
    <meta name="description" content="">
    <meta name="description" content="JavaScript 中有一个叫作闭包（Closure）的概念，非常有趣且适用，值得学习并整理为一篇博客。 为了更好理解闭包的作用，不妨看看我的这一篇博客关于 JS 变量提升（Hoisting）和函数提升现象的阐述。 作用域在 JavaScript 中，作用域（Scope）是当前代码执行的上下文，也即是值和表达式在其中可访问到的上下文。  如果一个变量或其它表达式不在当前作用域中，就会沿作用域链（">
<meta property="og:type" content="article">
<meta property="og:title" content="漫谈 JavsScript 闭包">
<meta property="og:url" content="https://lolipopj.github.io/2021/05/17/js-closure/index.html">
<meta property="og:site_name" content="Lolipop">
<meta property="og:description" content="JavaScript 中有一个叫作闭包（Closure）的概念，非常有趣且适用，值得学习并整理为一篇博客。 为了更好理解闭包的作用，不妨看看我的这一篇博客关于 JS 变量提升（Hoisting）和函数提升现象的阐述。 作用域在 JavaScript 中，作用域（Scope）是当前代码执行的上下文，也即是值和表达式在其中可访问到的上下文。  如果一个变量或其它表达式不在当前作用域中，就会沿作用域链（">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2021-05-17T16:00:00.000Z">
<meta property="article:modified_time" content="2021-05-17T16:00:00.000Z">
<meta property="article:author" content="Lolipop">
<meta property="article:tag" content="JavaScript">
<meta name="twitter:card" content="summary">
    <meta http-equiv="Cache-control" content="no-cache">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <link rel="icon" href="https://cdn.jsdelivr.net/gh/lolipopj/LolipopJ.github.io/static/assets/favicon.ico">
    
    <title>漫谈 JavsScript 闭包 · Lolipop&#39;s Studio</title>
    <!-- /*! loadCSS. [c]2017 Filament Group, Inc. MIT License */
/* This file is meant as a standalone workflow for
- testing support for link[rel=preload]
- enabling async CSS loading in browsers that do not support rel=preload
- applying rel preload css once loaded, whether supported or not.
*/ -->
<script>
    (function (w) {
        'use strict'
        // rel=preload support test
        if (!w.loadCSS) {
            w.loadCSS = function () {}
        }
        // define on the loadCSS obj
        var rp = (loadCSS.relpreload = {})
        // rel=preload feature support test
        // runs once and returns a function for compat purposes
        rp.support = (function () {
            var ret
            try {
                ret = w.document.createElement('link').relList.supports('preload')
            } catch (e) {
                ret = false
            }
            return function () {
                return ret
            }
        })()

        // if preload isn't supported, get an asynchronous load by using a non-matching media attribute
        // then change that media back to its intended value on load
        rp.bindMediaToggle = function (link) {
            // remember existing media attr for ultimate state, or default to 'all'
            var finalMedia = link.media || 'all'

            function enableStylesheet() {
                link.media = finalMedia
            }

            // bind load handlers to enable media
            if (link.addEventListener) {
                link.addEventListener('load', enableStylesheet)
            } else if (link.attachEvent) {
                link.attachEvent('onload', enableStylesheet)
            }

            // Set rel and non-applicable media type to start an async request
            // note: timeout allows this to happen async to let rendering continue in IE
            setTimeout(function () {
                link.rel = 'stylesheet'
                link.media = 'only x'
            })
            // also enable media after 3 seconds,
            // which will catch very old browsers (android 2.x, old firefox) that don't support onload on link
            setTimeout(enableStylesheet, 3000)
        }

        // loop through link elements in DOM
        rp.poly = function () {
            // double check this to prevent external calls from running
            if (rp.support()) {
                return
            }
            var links = w.document.getElementsByTagName('link')
            for (var i = 0; i < links.length; i++) {
                var link = links[i]
                // qualify links to those with rel=preload and as=style attrs
                if (
                    link.rel === 'preload' &&
                    link.getAttribute('as') === 'style' &&
                    !link.getAttribute('data-loadcss')
                ) {
                    // prevent rerunning on link
                    link.setAttribute('data-loadcss', true)
                    // bind listeners to toggle media back
                    rp.bindMediaToggle(link)
                }
            }
        }

        // if unsupported, run the polyfill
        if (!rp.support()) {
            // run once at least
            rp.poly()

            // rerun poly on an interval until onload
            var run = w.setInterval(rp.poly, 500)
            if (w.addEventListener) {
                w.addEventListener('load', function () {
                    rp.poly()
                    w.clearInterval(run)
                })
            } else if (w.attachEvent) {
                w.attachEvent('onload', function () {
                    rp.poly()
                    w.clearInterval(run)
                })
            }
        }

        // commonjs
        if (typeof exports !== 'undefined') {
            exports.loadCSS = loadCSS
        } else {
            w.loadCSS = loadCSS
        }
    })(typeof global !== 'undefined' ? global : this)
</script>

    <style type="text/css">
    @font-face {
        font-family: 'Oswald-Regular';
        src: url("/font/Oswald-Regular.ttf");
    }

    body {
        margin: 0;
    }

    header,
    footer,
    .back-top,
    .sidebar,
    .container,
    .site-intro-meta,
    .toc-wrapper {
        display: none;
    }

    .site-intro {
        position: relative;
        z-index: 3;
        width: 100%;
        /* height: 50vh; */
        overflow: hidden;
    }

    .site-intro-placeholder {
        position: absolute;
        z-index: -2;
        top: 0;
        left: 0;
        width: calc(100% + 300px);
        height: 100%;
        background: repeating-linear-gradient(-45deg, #444 0, #444 80px, #333 80px, #333 160px);
        background-position: center center;
        transform: translate3d(-226px, 0, 0);
        animation: gradient-move 2.5s ease-out 0s infinite;
    }

    @keyframes gradient-move {
        0% {
            transform: translate3d(-226px, 0, 0);
        }
        100% {
            transform: translate3d(0, 0, 0);
        }
    }
</style>

    <link rel="preload" href="/css/style.css?v=20211217" as="style" onload="this.onload=null;this.rel='stylesheet'">
    <link rel="preload" href="/css/dark.css?v=20211217" as="style">
    <link rel="stylesheet" href="/css/dark.css">
    <link rel="stylesheet" href="/css/mobile.css?v=20211217" media="(max-width: 960px)">
    <link rel="preload" href="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.css" as="style" onload="this.onload=null;this.rel='stylesheet'">
    <link rel="preload" href="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js" as="script">
    <link rel="preload" href="/scripts/main.js?v=20211217" as="script">
    <link rel="preload" href="/scripts/dark.js?v=20211217" as="script">
    <link rel="preload" href="/font/Oswald-Regular.ttf" as="font" crossorigin>
    <link rel="preload" href="https://at.alicdn.com/t/font_327081_1dta1rlogw17zaor.woff" as="font" crossorigin>
    <!-- algolia -->
    
        <script>
            var hits = JSON.parse('{"per_page":10}')
            var labels = JSON.parse('{"input_placeholder":"搜索博客","hits_empty":"Ops，我未能提供任何搜索结果：${query}","hits_stats":"在 ${time} ms 内找到了 ${hits} 个结果"}')

            var algolia = {
                applicationID: 'V9YD7AWBOS',
                apiKey: '5cb206cb0658a9daff865eef79de4bc4',
                indexName: 'lolipopJ.github.io',
                hits: hits,
                labels: labels
            }
        </script>
    
    <!-- 百度统计  -->
    
    <!-- 谷歌统计  -->
    
<meta name="generator" content="Hexo 5.4.1"><link rel="alternate" href="/atom.xml" title="Lolipop" type="application/atom+xml">
</head>

    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
    <script type="text/javascript">
        if (typeof window.$ == undefined) {
            console.warn('jquery load from jsdelivr failed, will load local script')
            document.write('<script src="/lib/jquery.min.js" />')
        }
    </script>
    
        <body class="post-body">
    
        <!-- header -->
        <header class="header header-mobile">
    <!-- top read progress line -->
    <div class="header-element">
        <div class="read-progress read-progress-feature"></div>
    </div>
    <!-- sidebar menu button -->
    <div class="header-element">
        
            <div class="header-sidebar-menu header-sidebar-menu-rounded">
        
            
                <i class="fas fa-bars"></i>
            
        </div>
    </div>
    <!-- header actions -->
    <div class="header-actions">
        <!-- theme mode switch button -->
        <span class="header-theme-btn header-element">
            <i class="fas fa-adjust"></i>
        </span>
        <!-- back to home page text -->
        <span class="home-link header-element">
            <a href=/>Lolipop's Studio.</a>
        </span>
    </div>
    <!-- toggle banner for post layout -->
    
        
            <div class="banner banner-clean">
        
            <div class="blog-title header-element">
                <a href="/">Lolipop&#39;s Studio.</a>
            </div>
            <div class="post-title header-element">
                <a href="#" class="post-name">漫谈 JavsScript 闭包</a>
            </div>
        </div>
    
</header>

        <!-- fixed footer -->
        <footer class="footer-fixed">
    <!-- back to top button -->
    <div class="footer-fixed-element">
        
            <div class="back-top back-top-hidden back-top-rounded">
        
        
            <i class="fas fa-chevron-up"></i>
        
        </div>
    </div>
</footer>

        <!-- wrapper -->
        <div class="wrapper">
            <div class="site-intro" style="







    height:50vh;

">
    
    <!-- 主页  -->
    
        
    <!-- 404页  -->
            
    <div class="site-intro-placeholder"></div>
    <div class="site-intro-img" style="background-image: url(https://source.unsplash.com/1600x900/?coder)"></div>
    <div class="site-intro-meta">
        <!-- 标题  -->
        <h1 class="intro-title">
            <!-- 主页  -->
            
                漫谈 JavsScript 闭包
            <!-- 404 -->
            
        </h1>
        <!-- 副标题 -->
        <p class="intro-subtitle">
            <!-- 主页副标题  -->
            
                
            <!-- 404 -->
            
        </p>
        <!-- 文章页 meta -->
        
            <div class="post-intros">
                <!-- 文章页标签  -->
                
                    <div class= post-intro-tags >
    
        
        
            
        
        
        <span class="post-category" data-categories="技术琐事"">
            <i class="fas fa-folder post-category-icon"></i>
            <span class="post-category-text">
                技术琐事
            </span>
        </span>
    
    
        <a class="post-tag" href="javascript:void(0);" data-tags="JavaScript">JavaScript</a>
    
</div>

                
                
                    <div class="post-intro-read">
                        <span>字数统计: <span class="post-count word-count">3.4k</span>阅读时长: <span class="post-count reading-time">13 min</span></span>
                    </div>
                
                <div class="post-intro-meta">
                    <!-- 撰写日期 -->
                    <span class="iconfont-archer post-intro-calander">&#xe676;</span>
                    <span class="post-intro-time">2021/05/18</span>
                    <!-- busuanzi -->
                    
                        <span id="busuanzi_container_page_pv" class="busuanzi-pv">
                            <span class="iconfont-archer post-intro-busuanzi">&#xe602;</span>
                            <span id="busuanzi_value_page_pv"></span>
                        </span>
                    
                    <!-- 文章分享 -->
                    <span class="share-wrapper">
                        <span class="iconfont-archer share-icon">&#xe71d;</span>
                        <span class="share-text">Share</span>
                        <ul class="share-list">
                            <li class="iconfont-archer share-qr" data-type="qr">&#xe75b;
                                <div class="share-qrcode"></div>
                            </li>
                            <li class="iconfont-archer" data-type="weibo">&#xe619;</li>
                            <li class="iconfont-archer" data-type="qzone">&#xe62e;</li>
                            <li class="iconfont-archer" data-type="twitter">&#xe634;</li>
                            <li class="iconfont-archer" data-type="facebook">&#xe67a;</li>
                        </ul>
                    </span>
                </div>
            </div>
        
    </div>
</div>

            <script>
  // get user agent
  function getBrowserVersions() {
    var u = window.navigator.userAgent
    return {
      userAgent: u,
      trident: u.indexOf('Trident') > -1, //IE内核
      presto: u.indexOf('Presto') > -1, //opera内核
      webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
      gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, //火狐内核
      mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否为移动终端
      ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
      android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android终端或者uc浏览器
      iPhone: u.indexOf('iPhone') > -1 || u.indexOf('Mac') > -1, //是否为iPhone或者安卓QQ浏览器
      iPad: u.indexOf('iPad') > -1, //是否为iPad
      webApp: u.indexOf('Safari') == -1, //是否为web应用程序，没有头部与底部
      weixin: u.indexOf('MicroMessenger') == -1, //是否为微信浏览器
      uc: u.indexOf('UCBrowser') > -1, //是否为android下的UC浏览器
    }
  }
  var browser = {
    versions: getBrowserVersions(),
  }
  console.log('userAgent: ' + browser.versions.userAgent)

  // callback
  function fontLoaded() {
    console.log('font loaded')
    if (document.getElementsByClassName('site-intro-meta')) {
      document
        .getElementsByClassName('intro-title')[0]
        .classList.add('intro-fade-in')
      document
        .getElementsByClassName('intro-subtitle')[0]
        .classList.add('intro-fade-in')
      var postIntros = document.getElementsByClassName('post-intros')[0]
      if (postIntros) {
        postIntros.classList.add('post-fade-in')
      }
    }
  }

  // UC不支持跨域，所以直接显示
  function asyncCb() {
    if (browser.versions.uc) {
      console.log('UCBrowser')
      fontLoaded()
    } else {
      WebFont.load({
        custom: {
          families: ['Oswald-Regular'],
        },
        loading: function () {
          // 所有字体开始加载
          // console.log('font loading');
        },
        active: function () {
          // 所有字体已渲染
          fontLoaded()
        },
        inactive: function () {
          // 字体预加载失败，无效字体或浏览器不支持加载
          console.log('inactive: timeout')
          fontLoaded()
        },
        timeout: 5000, // Set the timeout to two seconds
      })
    }
  }

  function asyncErr() {
    console.warn('script load from CDN failed, will load local script')
  }

  // load webfont-loader async, and add callback function
  function async(u, cb, err) {
    var d = document,
      t = 'script',
      o = d.createElement(t),
      s = d.getElementsByTagName(t)[0]
    o.src = u
    if (cb) {
      o.addEventListener(
        'load',
        function (e) {
          cb(null, e)
        },
        false
      )
    }
    if (err) {
      o.addEventListener(
        'error',
        function (e) {
          err(null, e)
        },
        false
      )
    }
    s.parentNode.insertBefore(o, s)
  }

  var asyncLoadWithFallBack = function (arr, success, reject) {
    var currReject = function () {
      reject()
      arr.shift()
      if (arr.length) async(arr[0], success, currReject)
    }

    async(arr[0], success, currReject)
  }

  asyncLoadWithFallBack(
    [
      'https://cdn.jsdelivr.net/npm/webfontloader@1.6.28/webfontloader.min.js',
      'https://cdn.bootcss.com/webfont/1.6.28/webfontloader.js',
      "/lib/webfontloader.min.js",
    ],
    asyncCb,
    asyncErr
  )
</script>

            <img class="loading" src="/assets/loading.svg" style="display: block; margin: 6rem auto 0 auto; width: 6rem; height: 6rem;" />
            <div class="container container-unloaded">
                <main class="main post-page">
    <article class="article-entry">
        <p>JavaScript 中有一个叫作闭包（Closure）的概念，非常有趣且适用，值得学习并整理为一篇博客。</p>
<p>为了更好理解闭包的作用，不妨看看我的<a href="/2021/05/10/js-hoisting/" title="这一篇博客">这一篇博客</a>关于 JS 变量提升（Hoisting）和函数提升现象的阐述。</p>
<h2 id="作用域"><a href="#作用域" class="headerlink" title="作用域"></a>作用域</h2><p>在 JavaScript 中，<strong>作用域</strong>（Scope）是当前代码执行的上下文，也即是值和表达式在其中可访问到的上下文。</p>
<ul>
<li>如果一个变量或其它表达式不在当前作用域中，就会沿<strong>作用域链</strong>（Scope Chain）往父作用域搜索。如果也仍未找到它的话，那么它就是不可用的。</li>
<li>最顶级的父作用域是全局对象。</li>
<li>父作用域不能引用子作用域中的变量和定义。</li>
</ul>
<p>目前，作用域有三种：<strong>全局作用域</strong>和<strong>函数作用域</strong>，以及 ES6 新增的<strong>块级作用域</strong>。</p>
<h3 id="作用域与执行上下文"><a href="#作用域与执行上下文" class="headerlink" title="作用域与执行上下文"></a>作用域与执行上下文</h3><p>作用域与<strong>执行上下文</strong>（Context）是两个不同的概念。JavaScript 系解释型语言，执行分为解释阶段和执行阶段两个阶段，两个阶段所完成的行为大抵如下：</p>
<ul>
<li>解释阶段：<ol>
<li>词法分析；</li>
<li>语法分析；</li>
<li><strong>确定作用域规则</strong>。</li>
</ol>
</li>
<li>执行阶段：<ol>
<li><strong>创建执行上下文</strong>；</li>
<li>执行函数代码；</li>
<li>垃圾回收。</li>
</ol>
</li>
</ul>
<p>可以看见，在解释阶段就已经确定了作用域规则，而在执行阶段才创建了执行上下文。因而作用域在定义时就确定，不会发生改变；执行上下文在运行时确定，可以发生改变。</p>
<h3 id="全局作用域和函数作用域"><a href="#全局作用域和函数作用域" class="headerlink" title="全局作用域和函数作用域"></a>全局作用域和函数作用域</h3><p>最外层函数和在最外层函数外边定义的变量拥有全局作用域，而函数内部定义的其他函数和变量拥有函数作用域。如：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> outVar = <span class="string">&#x27;outVar&#x27;</span></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">outFunc</span>(<span class="params"></span>) &#123;</span><br><span class="line">    <span class="keyword">var</span> inVar = <span class="string">&#x27;inVar&#x27;</span></span><br><span class="line">    <span class="keyword">function</span> <span class="title function_">inFunc</span>(<span class="params"></span>) &#123;</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(outVar, inVar)</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="title function_">inFunc</span>()</span><br><span class="line">&#125;</span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(outVar) <span class="comment">// outVar</span></span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(inVar) <span class="comment">// Uncaught ReferenceError: inVar is not defined</span></span><br><span class="line"><span class="title function_">outFunc</span>() <span class="comment">// outVar inVar</span></span><br><span class="line"><span class="title function_">inFunc</span>() <span class="comment">// Uncaught ReferenceError: inFunc is not defined</span></span><br></pre></td></tr></table></figure>

<p>在最外层，我们可以正常打印 <code>outVar</code> 和调用 <code>outFunc()</code> 方法，但是在尝试直接调用 <code>outFunc()</code> 方法中所定义的 <code>inVar</code> 和 <code>inFunc()</code> 方法时，发生报错。此外，在 <code>inFunc()</code> 方法中，成功在父作用域找到并打印出了 <code>outVar</code> 的值。</p>
<p>所有未定义而直接赋值的变量会自动声明为全局变量，拥有全局作用域。如：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">function</span> <span class="title function_">outFunc</span>(<span class="params"></span>) &#123;</span><br><span class="line">    globalInVar = <span class="string">&#x27;globalInVar&#x27;</span></span><br><span class="line">    <span class="keyword">var</span> invar = <span class="string">&#x27;inVar&#x27;</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 执行这个函数以赋值</span></span><br><span class="line"><span class="title function_">outFunc</span>()</span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(globalInVar) <span class="comment">// globalInVar</span></span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(invar) <span class="comment">// Uncaught ReferenceError: invar is not defined</span></span><br></pre></td></tr></table></figure>

<p>我们在 <code>outFunc()</code> 方法中未使用 <code>var</code> 声明而直接给 <code>globalInVar</code> 变量进行赋值，它将声明为全局变量，并能在最外层直接打印出来。应当避免此类声明的存在，在 <code>ESLint</code> 等代码质量检查工具中，会标注此类错误。</p>
<p>接下来看一段非常经典的代码案例：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">function</span> <span class="title function_">getArr</span>(<span class="params"></span>) &#123;</span><br><span class="line">    <span class="keyword">var</span> arr = []</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">var</span> i = <span class="number">0</span>; i &lt; <span class="number">5</span>; i++) &#123;</span><br><span class="line">        arr.<span class="title function_">push</span>(<span class="keyword">function</span>(<span class="params"></span>) &#123;</span><br><span class="line">            <span class="keyword">return</span> i</span><br><span class="line">        &#125;)</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> arr</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">var</span> testArr = <span class="title function_">getArr</span>()</span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(testArr[<span class="number">2</span>]()) <span class="comment">// 5</span></span><br></pre></td></tr></table></figure>

<p>我们将方法传入到数组中，期望调用方法返回的值为当前数组的索引值。在调用 <code>testArr[2]()</code> 时，期望得到的返回值为 <code>2</code>，但实际返回的值是 <code>5</code>，为什么？</p>
<p>这是由于在 <code>for</code> 循环中我们使用 <code>var</code> 声明的变量 <code>i</code> 会发生变量提升，其作用域为 <code>getArr()</code> 这个函数作用域。在调用数组中存储的函数时，我们已经完成了循环，此时 <code>i</code> 的值变成了 <code>5</code>，则无论调用数组的哪个函数都会打印出现在的值 <code>5</code>。上面的代码使用简化的方式编写，相当于：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> arr = []</span><br><span class="line"><span class="keyword">var</span> i <span class="comment">// 变量提升，我们在 for 循环中声明的变量在全局可访问</span></span><br><span class="line"><span class="keyword">for</span> (i = <span class="number">0</span>; i &lt; <span class="number">5</span>; i++) &#123;</span><br><span class="line">    arr.<span class="title function_">push</span>(<span class="keyword">function</span>(<span class="params"></span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> i</span><br><span class="line">    &#125;)</span><br><span class="line">&#125;</span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(arr[<span class="number">2</span>]()) <span class="comment">// 5</span></span><br><span class="line"><span class="comment">// console.log(i) // 5</span></span><br></pre></td></tr></table></figure>

<p>那么，现在的问题是，要如何在函数内部保存（或记住）一个从外部传入的值，在调用的时候能正确打印出我们想要的结果呢？</p>
<p>ES6 中提出了块级作用域，可以顺利解决这个问题。</p>
<h3 id="块级作用域"><a href="#块级作用域" class="headerlink" title="块级作用域"></a>块级作用域</h3><p>与声明的变量只能是全局或整个函数块的 <code>var</code> 命令不同，<code>let</code> 和 <code>const</code> 命令声明的变量、语句和表达式作用域可以限制在块级以内。例如：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">    <span class="keyword">var</span> varVar = <span class="string">&#x27;varVar&#x27;</span></span><br><span class="line">    <span class="keyword">let</span> letVar = <span class="string">&#x27;letVar&#x27;</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(varVar) <span class="comment">// varVar</span></span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(letVar) <span class="comment">// Uncaught ReferenceError: letVar is not defined</span></span><br></pre></td></tr></table></figure>

<p>在 ES6 以前，不存在块级作用域，使用 <code>var</code> 命令声明的在 <code>for</code>, <code>while</code> 等内部的变量都会提升为外部作用域的变量。</p>
<p>现在，我们就可以使用块级作用域替换刚刚的函数作用域了：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">function</span> <span class="title function_">getArr</span>(<span class="params"></span>) &#123;</span><br><span class="line">    <span class="keyword">const</span> arr = []</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; <span class="number">5</span>; i++) &#123; <span class="comment">// 使用 let 替换 var</span></span><br><span class="line">        arr.<span class="title function_">push</span>(<span class="keyword">function</span>(<span class="params"></span>) &#123;</span><br><span class="line">            <span class="keyword">return</span> i</span><br><span class="line">        &#125;)</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> arr</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">const</span> testArr = <span class="title function_">getArr</span>()</span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(testArr[<span class="number">2</span>]()) <span class="comment">// 2</span></span><br></pre></td></tr></table></figure>

<p>使用 <code>let</code> 命令声明的变量 <code>i</code> 在循环中拥有块级作用域，每次循环时每个返回的函数中引用的都是其对应块级作用域的变量。上面的代码使用简化的方式编写，相当于：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> arr = []</span><br><span class="line"><span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; <span class="number">5</span>; i++) &#123;</span><br><span class="line">    <span class="keyword">const</span> n = i <span class="comment">// 声明的变量仅在 for 循环的块作用域可访问</span></span><br><span class="line">    arr.<span class="title function_">push</span>(<span class="keyword">function</span>(<span class="params"></span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> n</span><br><span class="line">    &#125;)</span><br><span class="line">&#125;</span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(arr[<span class="number">2</span>]()) <span class="comment">// 2</span></span><br><span class="line"><span class="comment">// console.log(i) // Uncaught ReferenceError: i is not defined</span></span><br></pre></td></tr></table></figure>

<p>而在 ES6 之前，就需要用到了这篇博文真正的主角——闭包。</p>
<h2 id="什么是闭包"><a href="#什么是闭包" class="headerlink" title="什么是闭包"></a>什么是闭包</h2><p>由于 JavaScript 的链式作用域（Chain Scope）结构，父对象的所有变量都对子变量可见，反之则不成立。出于某种原因，我们有时候需要得到函数内的局部变量，就需要使用变通的方法实现：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 子对象的变量对父对象不可见</span></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">outerFunc</span>(<span class="params"></span>) &#123;</span><br><span class="line">    <span class="keyword">var</span> value = <span class="number">100</span></span><br><span class="line">    <span class="keyword">function</span> <span class="title function_">innerFunc</span>(<span class="params"></span>) &#123;</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(value)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="title function_">innerFunc</span>() <span class="comment">// Uncaught ReferenceError: innerFunc is not defined</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 变通的方法</span></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">outerFunc</span>(<span class="params"></span>) &#123;</span><br><span class="line">    <span class="keyword">var</span> value = <span class="number">100</span></span><br><span class="line">    <span class="keyword">function</span> <span class="title function_">innerFunc</span>(<span class="params"></span>) &#123;</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(value)</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> innerFunc <span class="comment">// 将内部定义的方法返回</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">var</span> visitValue = <span class="title function_">outerFunc</span>()</span><br><span class="line"><span class="title function_">visitValue</span>() <span class="comment">// 100</span></span><br></pre></td></tr></table></figure>

<p>在一些编程语言中，一个函数的局部变量仅存在于此函数的执行期间。那么一旦 <code>outerFunc()</code> 执行完毕，您可能会认为函数内部定义的变量 <code>value</code> 将不能够再访问。然而，在 JavaScript 中这段代码能够顺利执行并打印出结果。</p>
<p>这是由于 JavaScript 中的函数会形成<strong>闭包</strong>。</p>
<blockquote>
<p>一个函数和对其周围状态（lexical environment，词法环境）的引用捆绑在一起（或者说函数被引用包围），这样的组合就是闭包（closure）。也就是说，闭包让你可以在一个内层函数中访问到其外层函数的作用域。在 JavaScript 中，每当创建一个函数，闭包就会在函数创建的同时被创建出来。<br>A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function’s scope from an inner function. In JavaScript, closures are created every time a function is created, at function creation time.</p>
</blockquote>
<p>闭包是由函数以及声明该函数的词法环境组合而成的。该环境包含了这个闭包创建时作用域内的所有局部变量。从本质上来说，闭包可以看作将一个函数的内部和外部连接起来的桥梁。</p>
<p>在上面的代码中，变量 <code>visitValue</code> 是执行 <code>outerFunc()</code> 时创建的对 <code>innerFunc</code> 函数实例的引用，而 <code>innerFunc</code> 实例维持了一个对它的词法环境的引用，在这个词法环境中存在着变量 <code>value</code>。因此，当我们执行 <code>visitValue()</code> 时，变量 <code>value</code> 是可用的，最后我们成功在控制台打印出了它的值。</p>
<p>那么，为了解决在前文提出的不存在块级作用域的问题，我们可以像这样编写代码：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">function</span> <span class="title function_">getArr</span>(<span class="params"></span>) &#123;</span><br><span class="line">    <span class="keyword">var</span> arr = []</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">var</span> i = <span class="number">0</span>; i &lt; <span class="number">5</span>; i++) &#123;</span><br><span class="line">        arr.<span class="title function_">push</span>((<span class="keyword">function</span>(<span class="params">n</span>) &#123; <span class="comment">// n 的作用域为函数作用域</span></span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">function</span>(<span class="params"></span>) &#123; <span class="comment">// 返回一个函数</span></span><br><span class="line">                <span class="keyword">return</span> n <span class="comment">// 调用函数返回的值为传入的 n 的值</span></span><br><span class="line">            &#125;</span><br><span class="line">        &#125;)(i)) <span class="comment">// 传入当前的 i 值</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> arr</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">var</span> testArr = <span class="title function_">getArr</span>()</span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(testArr[<span class="number">2</span>]()) <span class="comment">// 2</span></span><br></pre></td></tr></table></figure>

<p>对于上面的 <code>for</code> 循环，相当于执行了下述代码：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">arr[<span class="number">0</span>] = (<span class="keyword">function</span>(<span class="params">n</span>) &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">function</span>(<span class="params"></span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> n</span><br><span class="line">    &#125;</span><br><span class="line">&#125;)(<span class="number">0</span>)</span><br><span class="line">arr[<span class="number">1</span>] = (<span class="keyword">function</span>(<span class="params">n</span>) &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">function</span>(<span class="params"></span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> n</span><br><span class="line">    &#125;</span><br><span class="line">&#125;)(<span class="number">1</span>)</span><br><span class="line">arr[<span class="number">2</span>] = (<span class="keyword">function</span>(<span class="params">n</span>) &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">function</span>(<span class="params"></span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> n</span><br><span class="line">    &#125;</span><br><span class="line">&#125;)(<span class="number">2</span>)</span><br><span class="line"><span class="comment">// 下略</span></span><br><span class="line"></span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(arr[<span class="number">2</span>]()) <span class="comment">// 2</span></span><br></pre></td></tr></table></figure>

<p>这样一来，数组中的每个函数分别处于一个立即执行函数的<strong>函数作用域</strong>中，这个立即执行的函数传入了每次循环时变量 <code>i</code> 的值。于是，当我们调用数组中的函数时，将返回<strong>传入时</strong>的 <code>i</code> 值，而不是循环结束后的 <code>i</code> 值。</p>
<blockquote>
<p>“JavaScript 中闭包无处不在，你只需要能够识别并拥抱它。”<br>“最后你恍然大悟：原来在我的代码中已经到处都是闭包了，现在我终于能理解他们了。<br>“理解闭包就好像 Neo 第一次见到矩阵一样。”</p>
</blockquote>
<p><em>You Don’t Know Javascript</em> 中如是写道。</p>
<h2 id="如何使用闭包"><a href="#如何使用闭包" class="headerlink" title="如何使用闭包"></a>如何使用闭包</h2><p>如果不是某些特定任务需要使用到闭包，那么在函数中创建另一个函数是不明智的。闭包会使得函数中的变量保存在<strong>内存</strong>中，可能造成性能问题。</p>
<h3 id="函数防抖和节流"><a href="#函数防抖和节流" class="headerlink" title="函数防抖和节流"></a>函数防抖和节流</h3><p>函数防抖和函数节流就是典型的闭包用例，我在<a href="/2021/05/07/js-debounce-throttle/" title="这一篇博客">这一篇博客</a>里对它们进行了编写。</p>
<h3 id="函数工厂"><a href="#函数工厂" class="headerlink" title="函数工厂"></a>函数工厂</h3><p>这是一个函数工厂的示例：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">function</span> <span class="title function_">makeAdder</span>(<span class="params">x</span>) &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">function</span>(<span class="params">y</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> x + y</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> add5 = <span class="title function_">makeAdder</span>(<span class="number">5</span>)</span><br><span class="line"><span class="keyword">var</span> add10 = <span class="title function_">makeAdder</span>(<span class="number">10</span>)</span><br><span class="line"></span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="title function_">add5</span>(<span class="number">2</span>)) <span class="comment">// 7</span></span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="title function_">add10</span>(<span class="number">2</span>)) <span class="comment">// 12</span></span><br></pre></td></tr></table></figure>

<p>我们定义了一个函数 <code>makeAdder(x)</code>，它接受一个参数 <code>x</code>，并返回一个新的函数。返回的这个函数接受参数 <code>y</code>，并返回 <code>x + y</code> 的值。接着，我们创建了两个新函数 <code>add5</code> 和 <code>add10</code>，一个将它的参数与 <code>5</code> 求和，另一个与 <code>10</code> 求和。</p>
<p><code>add5</code> 和 <code>add10</code> 都是闭包，它们共享相同的函数定义，但是保存了不同的词法环境。在 <code>add5</code> 的词法环境中，<code>x</code> 的值为 <code>5</code>；而在 <code>add10</code> 中，<code>x</code> 为 <code>10</code>。</p>
<h3 id="面向对象编程"><a href="#面向对象编程" class="headerlink" title="面向对象编程"></a>面向对象编程</h3><p>我们可以用闭包来模拟<strong>私有</strong>属性和方法，就像面向对象编程语言中类的私有属性和方法的编写一样。以构建 <code>Rectangle</code> 矩形类为例：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> <span class="title class_">Rectangle</span> = <span class="keyword">function</span>(<span class="params">height, width</span>) &#123;</span><br><span class="line">    <span class="keyword">var</span> height = height <span class="comment">// 私有的高属性</span></span><br><span class="line">    <span class="keyword">var</span> width = width <span class="comment">// 私有的宽属性</span></span><br><span class="line">    <span class="keyword">function</span> <span class="title function_">calcArea</span>(<span class="params"></span>) &#123; <span class="comment">// 私有的计算面积方法</span></span><br><span class="line">        <span class="keyword">return</span> height * width</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">function</span> <span class="title function_">setHeight</span>(<span class="params">h</span>) &#123; <span class="comment">// 私有的设置高方法</span></span><br><span class="line">        height = h</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">function</span> <span class="title function_">setWidth</span>(<span class="params">w</span>) &#123; <span class="comment">// 私有的设置宽方法</span></span><br><span class="line">        width = w</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> &#123; <span class="comment">// 返回一个对象，对象可以访问到闭包的作用域</span></span><br><span class="line">        <span class="keyword">get</span> <span class="title function_">area</span>() &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="title function_">calcArea</span>()</span><br><span class="line">        &#125;,</span><br><span class="line">        <span class="attr">setHeight</span>: <span class="keyword">function</span>(<span class="params">h</span>) &#123;</span><br><span class="line">            <span class="title function_">setHeight</span>(h)</span><br><span class="line">        &#125;,</span><br><span class="line">        <span class="attr">setWidth</span>: <span class="keyword">function</span>(<span class="params">w</span>) &#123;</span><br><span class="line">            <span class="title function_">setWidth</span>(w)</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> square = <span class="title class_">Rectangle</span>(<span class="number">5</span>, <span class="number">5</span>)</span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(square.<span class="property">area</span>) <span class="comment">// 25</span></span><br><span class="line"></span><br><span class="line">square.<span class="title function_">setHeight</span>(<span class="number">10</span>)</span><br><span class="line">square.<span class="title function_">setWidth</span>(<span class="number">10</span>)</span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(square.<span class="property">area</span>) <span class="comment">// 100</span></span><br><span class="line"></span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(square.<span class="property">height</span>) <span class="comment">// undefined</span></span><br></pre></td></tr></table></figure>

<p>在上面的代码中，我们使用了闭包来定义公共函数，并令这些公共函数访问到私有函数和变量。这个方式又称模块模式（Module Pattern）。</p>
<p>在 ES6 中，可以用 <code>class</code> 语法糖来声明类。上面的代码相当于：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Rectangle</span> &#123;</span><br><span class="line">    #height</span><br><span class="line">    #width</span><br><span class="line">    <span class="comment">// Constructor</span></span><br><span class="line">    <span class="title function_">constructor</span>(<span class="params">height, width</span>) &#123;</span><br><span class="line">        <span class="variable language_">this</span>.#height = height</span><br><span class="line">        <span class="variable language_">this</span>.#width = width</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// Getter</span></span><br><span class="line">    <span class="keyword">get</span> <span class="title function_">area</span>() &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="variable language_">this</span>.<span class="title function_">calcArea</span>()</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// Method</span></span><br><span class="line">    <span class="title function_">calcArea</span>(<span class="params"></span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="variable language_">this</span>.#height * <span class="variable language_">this</span>.#width</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="title function_">setHeight</span>(<span class="params">h</span>) &#123;</span><br><span class="line">        <span class="variable language_">this</span>.#height = h</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="title function_">setWidth</span>(<span class="params">w</span>) &#123;</span><br><span class="line">        <span class="variable language_">this</span>.#width = w</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> square = <span class="keyword">new</span> <span class="title class_">Rectangle</span>(<span class="number">5</span>, <span class="number">5</span>) <span class="comment">// 使用 new 关键字来创建对象</span></span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(square.<span class="property">area</span>) <span class="comment">// 25</span></span><br><span class="line"></span><br><span class="line">square.<span class="title function_">setHeight</span>(<span class="number">10</span>)</span><br><span class="line">square.<span class="title function_">setWidth</span>(<span class="number">10</span>)</span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(square.<span class="property">area</span>) <span class="comment">// 100</span></span><br><span class="line"></span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(square.<span class="property">height</span>) <span class="comment">// undefined</span></span><br></pre></td></tr></table></figure>

<p>在 <code>class</code> 内，私有属性 <code>height</code> 和 <code>width</code> 需要在前面加上 <code>#</code> 并在开头显示声明出来。</p>
<p>当然，相比闭包的方式，使用 <code>class</code> 的声明更加直观，值得推广使用。</p>
<p>值得补充的是，假如不需要在对象中使用私有声明，而是使用公用声明，应当避免使用闭包。同样以构建 <code>PublicRectangle</code> 矩形类为例：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> <span class="title class_">PublicRectangle</span> = <span class="keyword">function</span>(<span class="params">height, width</span>) &#123;</span><br><span class="line">    <span class="keyword">return</span> &#123; <span class="comment">// 将矩形的高和宽作为返回对象的可访问属性</span></span><br><span class="line">        <span class="attr">height</span>: height,</span><br><span class="line">        <span class="attr">width</span>: width,</span><br><span class="line">        <span class="keyword">get</span> <span class="title function_">area</span>() &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="variable language_">this</span>.<span class="property">height</span> * <span class="variable language_">this</span>.<span class="property">width</span></span><br><span class="line">        &#125;,</span><br><span class="line">        <span class="attr">setHeight</span>: <span class="keyword">function</span>(<span class="params">h</span>) &#123;</span><br><span class="line">            <span class="variable language_">this</span>.<span class="property">height</span> = h</span><br><span class="line">        &#125;,</span><br><span class="line">        <span class="attr">setWidth</span>: <span class="keyword">function</span>(<span class="params">w</span>) &#123;</span><br><span class="line">            <span class="variable language_">this</span>.<span class="property">width</span> = w</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> square = <span class="title class_">PublicRectangle</span>(<span class="number">5</span>, <span class="number">5</span>)</span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(square.<span class="property">area</span>) <span class="comment">// 25</span></span><br><span class="line"></span><br><span class="line">square.<span class="title function_">setHeight</span>(<span class="number">10</span>)</span><br><span class="line">square.<span class="title function_">setWidth</span>(<span class="number">10</span>)</span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(square.<span class="property">area</span>) <span class="comment">// 100</span></span><br><span class="line"></span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(square.<span class="property">height</span>) <span class="comment">// 10</span></span><br></pre></td></tr></table></figure>

<p>上面的代码中我们并没有利用到闭包的好处，反而在每次调用构造器时都重新赋值一遍方法。因此在这里不妨变为添加<strong>原型方法</strong>的方式：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> <span class="title class_">PublicRectangle</span> = <span class="keyword">function</span>(<span class="params">height, width</span>) &#123;</span><br><span class="line">    <span class="variable language_">this</span>.<span class="property">height</span> = height</span><br><span class="line">    <span class="variable language_">this</span>.<span class="property">width</span> = width</span><br><span class="line">&#125;</span><br><span class="line"><span class="title class_">Object</span>.<span class="title function_">defineProperty</span>(<span class="title class_">PublicRectangle</span>.<span class="property"><span class="keyword">prototype</span></span>, <span class="string">&#x27;area&#x27;</span>, &#123; <span class="comment">// 为 PublicRectangle 原型添加 area 的 getter</span></span><br><span class="line">    <span class="title function_">get</span>(<span class="params"></span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="variable language_">this</span>.<span class="property">height</span> * <span class="variable language_">this</span>.<span class="property">width</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;)</span><br><span class="line"><span class="title class_">PublicRectangle</span>.<span class="property"><span class="keyword">prototype</span></span>.<span class="property">setHeight</span> = <span class="keyword">function</span>(<span class="params">h</span>) &#123;</span><br><span class="line">    <span class="variable language_">this</span>.<span class="property">height</span> = h</span><br><span class="line">&#125;</span><br><span class="line"><span class="title class_">PublicRectangle</span>.<span class="property"><span class="keyword">prototype</span></span>.<span class="property">setWidth</span> = <span class="keyword">function</span>(<span class="params">w</span>) &#123;</span><br><span class="line">    <span class="variable language_">this</span>.<span class="property">width</span> = w</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> square = <span class="keyword">new</span> <span class="title class_">PublicRectangle</span>(<span class="number">5</span>, <span class="number">5</span>) <span class="comment">// 应使用 new 关键字</span></span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(square.<span class="property">area</span>) <span class="comment">// 25</span></span><br><span class="line"></span><br><span class="line">square.<span class="title function_">setHeight</span>(<span class="number">10</span>)</span><br><span class="line">square.<span class="title function_">setWidth</span>(<span class="number">10</span>)</span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(square.<span class="property">area</span>) <span class="comment">// 100</span></span><br><span class="line"></span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(square.<span class="property">height</span>) <span class="comment">// 10</span></span><br></pre></td></tr></table></figure>

<h2 id="参考资料"><a href="#参考资料" class="headerlink" title="参考资料"></a>参考资料</h2><h3 id="技术博客（或问答）"><a href="#技术博客（或问答）" class="headerlink" title="技术博客（或问答）"></a>技术博客（或问答）</h3><ul>
<li><a target="_blank" rel="noopener" href="https://www.jianshu.com/p/ebb4eccb6625">闭包以及其ES6下的使用</a>, 2020-01-13</li>
<li><a target="_blank" rel="noopener" href="https://blog.fundebug.com/2019/03/15/understand-javascript-scope/">深入理解 JavaScript 作用域和作用域链</a>, 2019-03-15</li>
<li><a target="_blank" rel="noopener" href="https://juejin.cn/post/6844903747106111501">深入解析ES6中let和闭包</a>, 2018-12-25</li>
<li><a target="_blank" rel="noopener" href="https://segmentfault.com/q/1010000016598692">如何给js内建对象构造器添加getter和setter</a>, 2018-10-06</li>
<li><a target="_blank" rel="noopener" href="http://www.ruanyifeng.com/blog/2009/08/learning_javascript_closures.html">学习Javascript闭包（Closure）</a>, 2009-08-30</li>
</ul>
<h3 id="其它资料"><a href="#其它资料" class="headerlink" title="其它资料"></a>其它资料</h3><ul>
<li><a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Closures">闭包 - MDN</a></li>
<li><a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Classes">类 - MDN</a></li>
<li><a target="_blank" rel="noopener" href="https://github.com/getify/You-Dont-Know-JS">You Don’t Know Javascript</a></li>
</ul>

    </article>
    <!-- license -->
    
        <div class="license-wrapper">
            <p>原文作者：<a href="https://LolipopJ.github.io">Lolipop</a>
            <p>原文链接：<a href="https://lolipopj.github.io/2021/05/17/js-closure/">https://lolipopj.github.io/2021/05/17/js-closure/</a>
            <p>发表日期：<a href="https://lolipopj.github.io/2021/05/17/js-closure/">May 17th 2021, 4:00:00 pm</a>
            <p>更新日期：<a href="https://lolipopj.github.io/2021/05/17/js-closure/">May 17th 2021, 4:00:00 pm</a>
            <p>版权声明：本文采用<a rel="license noopener" target="_blank" href="http://creativecommons.org/licenses/by-nc/4.0/">知识共享署名-非商业性使用 4.0 国际许可协议</a>进行许可</p>
        </div>
    
    <!-- paginator -->
    <ul class="post-paginator">
        <li class="next">
            
                <div class="nextSlogan">Next Post</div>
                <a href="/2021/05/19/js-use-class/" title="漫谈 JavsScript 类（Class）的使用">
                    <div class="nextTitle">漫谈 JavsScript 类（Class）的使用</div>
                </a>
            
        </li>
        <li class="previous">
            
                <div class="prevSlogan">Previous Post</div>
                <a href="/2021/05/10/js-hoisting/" title="JavsScript 变量提升和函数提升">
                    <div class="prevTitle">JavsScript 变量提升和函数提升</div>
                </a>
            
        </li>
    </ul>
    <!-- comment -->
    
        <div class="post-comment">
            <!-- 来必力 City 版安装代码 -->


            

            

            
    <div id="gitalk-container"></div>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/gitalk@1.7.2/dist/gitalk.css">
    <script src="https://cdn.jsdelivr.net/npm/gitalk@1.7.2/dist/gitalk.min.js"></script>
    <script>
        let idOption = 'Mon May 17 2021 16:00:00 GMT+0000'
        
            idOption = location.pathname
        
        const gitalk = new Gitalk({
            clientID: '3e27d4e7935138a80cd8',
            clientSecret: 'cd3eda2bf0740e7a51b8b611ade908eb95590e45',
            repo: 'LolipopJ.github.io',
            owner: 'LolipopJ',
            admin: ["LolipopJ"],
            id: idOption,
            distractionFreeMode: false,
            createIssueManually: false,
        })
        gitalk.render('gitalk-container')
    </script>
    <noscript>为正常使用 Gitalk 评论功能，您需要激活 JavaScript</noscript>


            <!-- utteranc评论 -->


            <!-- partial('_partial/comment/changyan') -->
            <!--PC版-->


            
            

            

        </div>
    
    <!-- timeliness note -->
    <!-- idea from: https://hexo.fluid-dev.com/posts/hexo-injector/#%E6%96%87%E7%AB%A0%E6%97%B6%E6%95%88%E6%80%A7%E6%8F%90%E7%A4%BA -->
    
    <!-- Mathjax -->
    
</main>

                <!-- profile -->
                
            </div>
            <footer class="footer footer-unloaded">
    <!-- social  -->
    
        <div class="social">
            
    
        
            
                <a href="mailto:lolipop0703@qq.com" class="iconfont-archer email" title=email ></a>
            
        
    
        
            
                <a href="//github.com/LolipopJ" class="iconfont-archer github" target="_blank" title=github></a>
            
        
    
        
    
        
    
        
    
        
    
        
    
        
    
        
    
        
            
                <a href="https://twitter.com/Lolipop_0703" class="iconfont-archer twitter" target="_blank" title=twitter></a>
            
        
    
        
    
        
    
        
    
        
    
        
    
        
    
        
    
        
    
        
    
        
            
                <a href="/atom.xml" class="iconfont-archer rss" target="_blank" title=rss></a>
            
        
    


        </div>
    
    <!-- powered by Hexo  -->
    <div class="copyright">
        <span id="hexo-power">Powered by <a href="https://hexo.io/" target="_blank">Hexo</a></span><span class="iconfont-archer power">&#xe635;</span><span id="theme-info">theme <a href="https://github.com/fi3ework/hexo-theme-archer" target="_blank">Archer</a></span>
    </div>
    <!-- website approve for Chinese user -->
    
        <div class="website-approve">
            
                <span id="icp-approve" class="icp-approve">
                    <a href="https://beian.miit.gov.cn/" target="_blank">蜀ICP备 2021015698号</a>
                </span>
            
            
                
                <img class="beian-img" src="/assets/beian.png" />
                <span id="beian-approve" class="beian-approve">
                    <a href="http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=51010802001109" target="_blank">京公网安备 51010802001109号</a>
                </span>
            
        </div>
    
    <!-- 不蒜子  -->
    
        <div class="busuanzi-container">
            
             
                <span id="busuanzi_container_site_pv">PV: <span id="busuanzi_value_site_pv"></span> :)</span>
            
        </div>
    	
</footer>

        </div>
        <!-- toc -->
        
            <div class="toc-wrapper toc-wrapper-loding" style=







    top:50vh;

>
                <div class="toc-catalog">
                    <span class="iconfont-archer catalog-icon">&#xe613;</span><span>CATALOG</span>
                </div>
                <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BD%9C%E7%94%A8%E5%9F%9F"><span class="toc-number">1.</span> <span class="toc-text">作用域</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BD%9C%E7%94%A8%E5%9F%9F%E4%B8%8E%E6%89%A7%E8%A1%8C%E4%B8%8A%E4%B8%8B%E6%96%87"><span class="toc-number">1.1.</span> <span class="toc-text">作用域与执行上下文</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%85%A8%E5%B1%80%E4%BD%9C%E7%94%A8%E5%9F%9F%E5%92%8C%E5%87%BD%E6%95%B0%E4%BD%9C%E7%94%A8%E5%9F%9F"><span class="toc-number">1.2.</span> <span class="toc-text">全局作用域和函数作用域</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%9D%97%E7%BA%A7%E4%BD%9C%E7%94%A8%E5%9F%9F"><span class="toc-number">1.3.</span> <span class="toc-text">块级作用域</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BB%80%E4%B9%88%E6%98%AF%E9%97%AD%E5%8C%85"><span class="toc-number">2.</span> <span class="toc-text">什么是闭包</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%A6%82%E4%BD%95%E4%BD%BF%E7%94%A8%E9%97%AD%E5%8C%85"><span class="toc-number">3.</span> <span class="toc-text">如何使用闭包</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%87%BD%E6%95%B0%E9%98%B2%E6%8A%96%E5%92%8C%E8%8A%82%E6%B5%81"><span class="toc-number">3.1.</span> <span class="toc-text">函数防抖和节流</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%87%BD%E6%95%B0%E5%B7%A5%E5%8E%82"><span class="toc-number">3.2.</span> <span class="toc-text">函数工厂</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E9%9D%A2%E5%90%91%E5%AF%B9%E8%B1%A1%E7%BC%96%E7%A8%8B"><span class="toc-number">3.3.</span> <span class="toc-text">面向对象编程</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%8F%82%E8%80%83%E8%B5%84%E6%96%99"><span class="toc-number">4.</span> <span class="toc-text">参考资料</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%8A%80%E6%9C%AF%E5%8D%9A%E5%AE%A2%EF%BC%88%E6%88%96%E9%97%AE%E7%AD%94%EF%BC%89"><span class="toc-number">4.1.</span> <span class="toc-text">技术博客（或问答）</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%85%B6%E5%AE%83%E8%B5%84%E6%96%99"><span class="toc-number">4.2.</span> <span class="toc-text">其它资料</span></a></li></ol></li></ol>
            </div>
        
        <!-- sidebar -->
        <div class="sidebar sidebar-hide">
    <ul class="sidebar-tabs sidebar-tabs-active-0">
        <li class="sidebar-tab-archives"><span class="iconfont-archer">&#xe67d;</span><span class="tab-name">Archive</span></li>
        <li class="sidebar-tab-tags"><span class="iconfont-archer">&#xe61b;</span><span class="tab-name">Tag</span></li>
        <li class="sidebar-tab-categories"><span class="iconfont-archer">&#xe666;</span><span class="tab-name">Cate</span></li>
    </ul>
    <div class="sidebar-content sidebar-content-show-archive">
        <div class="sidebar-panel-archives">
    <!-- 在 ejs 中将 archive 按照时间排序 -->
    
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
    
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
    
    
    
    
    <div class="total-and-search">
        <div class="total-archive">
        Total : 31
        </div>
        <!-- search  -->
        
            <div class="site-search site-search-loading popup-trigger">
                <span class="iconfont-archer search-icon">&#xe627;</span>
            </div>
        
    </div>
    
    <div class="post-archive">
    
        
            
            
            <div class="archive-year"> 2022 </div>
            <ul class="year-list">
            
        
        <li class="archive-post-item">
            <span class="archive-post-date">02/12</span>
            <a class="archive-post-title" href="/2022/02/11/connect-with-pgsql/">连接到 Windows 端的 PostgreSQL 数据库</a>
        </li>
    
        
        <li class="archive-post-item">
            <span class="archive-post-date">01/13</span>
            <a class="archive-post-title" href="/2022/01/12/random-get-me-a-picture/">这位客官，要来一张我珍藏许久的图片吗</a>
        </li>
    
        
        <li class="archive-post-item">
            <span class="archive-post-date">01/09</span>
            <a class="archive-post-title" href="/2022/01/08/start-telegram-bot/">从零开始使用 Telegram Bot</a>
        </li>
    
        
            
            
                
                </ul>
            
            <div class="archive-year"> 2021 </div>
            <ul class="year-list">
            
        
        <li class="archive-post-item">
            <span class="archive-post-date">08/19</span>
            <a class="archive-post-title" href="/2021/08/18/build-my-resume/">把自己的简历做成 Web 页面</a>
        </li>
    
        
        <li class="archive-post-item">
            <span class="archive-post-date">08/13</span>
            <a class="archive-post-title" href="/2021/08/12/github-jsdelivr-hold-image/">使用 jsDelivr 加速 Github 仓库搭建自己的图床服务</a>
        </li>
    
        
        <li class="archive-post-item">
            <span class="archive-post-date">08/07</span>
            <a class="archive-post-title" href="/2021/08/06/editorconfig-prettier/">使用 EditorConfig 和 Prettier 优雅地配置 VSCode 代码格式化</a>
        </li>
    
        
        <li class="archive-post-item">
            <span class="archive-post-date">07/10</span>
            <a class="archive-post-title" href="/2021/07/09/switch-travis-to-github-workflow/">更换持续集成工具，从 Travis 到 Github Actions</a>
        </li>
    
        
        <li class="archive-post-item">
            <span class="archive-post-date">07/08</span>
            <a class="archive-post-title" href="/2021/07/07/browser-behind-visit-url/">在浏览器中输入 URL 到显示网页，背后发生了什么</a>
        </li>
    
        
        <li class="archive-post-item">
            <span class="archive-post-date">06/26</span>
            <a class="archive-post-title" href="/2021/06/25/web-font-for-hexo-theme-archer/">为 Archer 主题更换字体</a>
        </li>
    
        
        <li class="archive-post-item">
            <span class="archive-post-date">06/25</span>
            <a class="archive-post-title" href="/2021/06/24/website-deployment-docker-nginx/">使用基于 Docker 的 Nginx 部署静态网页项目</a>
        </li>
    
        
        <li class="archive-post-item">
            <span class="archive-post-date">06/09</span>
            <a class="archive-post-title" href="/2021/06/08/linux-project-v/">在 Linux 系统下启用 Project-V</a>
        </li>
    
        
        <li class="archive-post-item">
            <span class="archive-post-date">06/04</span>
            <a class="archive-post-title" href="/2021/06/03/euler-install-mysql/">在 Euler 系统上离线安装 MySQL 5.7</a>
        </li>
    
        
        <li class="archive-post-item">
            <span class="archive-post-date">05/20</span>
            <a class="archive-post-title" href="/2021/05/19/js-use-class/">漫谈 JavsScript 类（Class）的使用</a>
        </li>
    
        
        <li class="archive-post-item">
            <span class="archive-post-date">05/18</span>
            <a class="archive-post-title" href="/2021/05/17/js-closure/">漫谈 JavsScript 闭包</a>
        </li>
    
        
        <li class="archive-post-item">
            <span class="archive-post-date">05/11</span>
            <a class="archive-post-title" href="/2021/05/10/js-hoisting/">JavsScript 变量提升和函数提升</a>
        </li>
    
        
        <li class="archive-post-item">
            <span class="archive-post-date">05/08</span>
            <a class="archive-post-title" href="/2021/05/07/js-debounce-throttle/">函数防抖和节流，以及在 Vue 中的运用</a>
        </li>
    
        
        <li class="archive-post-item">
            <span class="archive-post-date">04/26</span>
            <a class="archive-post-title" href="/2021/04/25/windows-install-grpc/">Windows 系统编译安装基于 C++ 的 gRPC</a>
        </li>
    
        
        <li class="archive-post-item">
            <span class="archive-post-date">04/22</span>
            <a class="archive-post-title" href="/2021/04/21/linux-docker-install-grpc/">Linux 系统编译安装基于 C++ 的 gRPC</a>
        </li>
    
        
        <li class="archive-post-item">
            <span class="archive-post-date">04/20</span>
            <a class="archive-post-title" href="/2021/04/19/linux-docker-gcc-update/">Linux 容器更新或降级 GCC 版本</a>
        </li>
    
        
        <li class="archive-post-item">
            <span class="archive-post-date">03/29</span>
            <a class="archive-post-title" href="/2021/03/28/protobuf-learning/">Protobuf 学习笔记</a>
        </li>
    
        
        <li class="archive-post-item">
            <span class="archive-post-date">03/17</span>
            <a class="archive-post-title" href="/2021/03/16/amap-import-vue/">在 Nuxt.js 中引入高德地图并实现定位及逆地理编码</a>
        </li>
    
        
        <li class="archive-post-item">
            <span class="archive-post-date">03/16</span>
            <a class="archive-post-title" href="/2021/03/15/tencent-map-api-get-current-location/">使用腾讯位置服务进行 Web 前端定位</a>
        </li>
    
        
        <li class="archive-post-item">
            <span class="archive-post-date">03/10</span>
            <a class="archive-post-title" href="/2021/03/09/xxx-is-not-a-symbolic-link/">提示 *** is not a symbolic link 解决方案</a>
        </li>
    
        
        <li class="archive-post-item">
            <span class="archive-post-date">03/03</span>
            <a class="archive-post-title" href="/2021/03/02/nodejs-eslint-prettier/">Nuxt 项目配置 ESLint 和 Prettier 检查并规范代码质量与格式</a>
        </li>
    
        
        <li class="archive-post-item">
            <span class="archive-post-date">02/23</span>
            <a class="archive-post-title" href="/2021/02/22/write-md-parser/">Webpack 读取本地 Markdown 文件并进行预处理</a>
        </li>
    
        
        <li class="archive-post-item">
            <span class="archive-post-date">02/21</span>
            <a class="archive-post-title" href="/2021/02/20/tg-mtproto-one-click/">一键安装并配置 MTProto Proxy 代理 Telegram</a>
        </li>
    
        
        <li class="archive-post-item">
            <span class="archive-post-date">02/19</span>
            <a class="archive-post-title" href="/2021/02/18/hexo-github-actions-ci-cd/">使用 Github Actions 持续集成与部署 Hexo 博客</a>
        </li>
    
        
            
            
                
                </ul>
            
            <div class="archive-year"> 2020 </div>
            <ul class="year-list">
            
        
        <li class="archive-post-item">
            <span class="archive-post-date">12/29</span>
            <a class="archive-post-title" href="/2020/12/28/ISO-IEC-IEEE-42010-des/">IEEE 1471（ISO/IEC/IEEE 42010）架构描述方法</a>
        </li>
    
        
        <li class="archive-post-item">
            <span class="archive-post-date">09/28</span>
            <a class="archive-post-title" href="/2020/09/27/pytorch-install-windows-10/">PyTorch 在 Windows 10 系统下的环境配置及安装</a>
        </li>
    
        
            
            
                
                </ul>
            
            <div class="archive-year"> 2019 </div>
            <ul class="year-list">
            
        
        <li class="archive-post-item">
            <span class="archive-post-date">12/27</span>
            <a class="archive-post-title" href="/2019/12/26/archer-theme-update-log/">基于 Archer 主题的博客开发</a>
        </li>
    
        
        <li class="archive-post-item">
            <span class="archive-post-date">12/27</span>
            <a class="archive-post-title" href="/2019/12/26/hello-hexo-world/">Hello Hexo World</a>
        </li>
    
    </div>
</div>

        <div class="sidebar-panel-tags">
    <div class="sidebar-tags-name">
        
            <span class="sidebar-tag-name" data-tags="开发日志">
                <span class="iconfont-archer">&#xe606;</span>
                开发日志
            </span>
        
            <span class="sidebar-tag-name" data-tags="Vue-2">
                <span class="iconfont-archer">&#xe606;</span>
                Vue-2
            </span>
        
            <span class="sidebar-tag-name" data-tags="软件体系架构设计">
                <span class="iconfont-archer">&#xe606;</span>
                软件体系架构设计
            </span>
        
            <span class="sidebar-tag-name" data-tags="JavaScript">
                <span class="iconfont-archer">&#xe606;</span>
                JavaScript
            </span>
        
            <span class="sidebar-tag-name" data-tags="Node">
                <span class="iconfont-archer">&#xe606;</span>
                Node
            </span>
        
            <span class="sidebar-tag-name" data-tags="Nuxt">
                <span class="iconfont-archer">&#xe606;</span>
                Nuxt
            </span>
        
            <span class="sidebar-tag-name" data-tags="Promise">
                <span class="iconfont-archer">&#xe606;</span>
                Promise
            </span>
        
            <span class="sidebar-tag-name" data-tags="博客开发">
                <span class="iconfont-archer">&#xe606;</span>
                博客开发
            </span>
        
            <span class="sidebar-tag-name" data-tags="Hexo">
                <span class="iconfont-archer">&#xe606;</span>
                Hexo
            </span>
        
            <span class="sidebar-tag-name" data-tags="hexo-theme-archer">
                <span class="iconfont-archer">&#xe606;</span>
                hexo-theme-archer
            </span>
        
            <span class="sidebar-tag-name" data-tags="计算机网络">
                <span class="iconfont-archer">&#xe606;</span>
                计算机网络
            </span>
        
            <span class="sidebar-tag-name" data-tags="网络安全">
                <span class="iconfont-archer">&#xe606;</span>
                网络安全
            </span>
        
            <span class="sidebar-tag-name" data-tags="密码学">
                <span class="iconfont-archer">&#xe606;</span>
                密码学
            </span>
        
            <span class="sidebar-tag-name" data-tags="resume">
                <span class="iconfont-archer">&#xe606;</span>
                resume
            </span>
        
            <span class="sidebar-tag-name" data-tags="CSS">
                <span class="iconfont-archer">&#xe606;</span>
                CSS
            </span>
        
            <span class="sidebar-tag-name" data-tags="Github-actions">
                <span class="iconfont-archer">&#xe606;</span>
                Github-actions
            </span>
        
            <span class="sidebar-tag-name" data-tags="rxjs">
                <span class="iconfont-archer">&#xe606;</span>
                rxjs
            </span>
        
            <span class="sidebar-tag-name" data-tags="PostgreSQL">
                <span class="iconfont-archer">&#xe606;</span>
                PostgreSQL
            </span>
        
            <span class="sidebar-tag-name" data-tags="Windows">
                <span class="iconfont-archer">&#xe606;</span>
                Windows
            </span>
        
            <span class="sidebar-tag-name" data-tags="EditorConfig">
                <span class="iconfont-archer">&#xe606;</span>
                EditorConfig
            </span>
        
            <span class="sidebar-tag-name" data-tags="Prettier">
                <span class="iconfont-archer">&#xe606;</span>
                Prettier
            </span>
        
            <span class="sidebar-tag-name" data-tags="VSCode">
                <span class="iconfont-archer">&#xe606;</span>
                VSCode
            </span>
        
            <span class="sidebar-tag-name" data-tags="Linux">
                <span class="iconfont-archer">&#xe606;</span>
                Linux
            </span>
        
            <span class="sidebar-tag-name" data-tags="MySQL">
                <span class="iconfont-archer">&#xe606;</span>
                MySQL
            </span>
        
            <span class="sidebar-tag-name" data-tags="Github">
                <span class="iconfont-archer">&#xe606;</span>
                Github
            </span>
        
            <span class="sidebar-tag-name" data-tags="jsDiliver">
                <span class="iconfont-archer">&#xe606;</span>
                jsDiliver
            </span>
        
            <span class="sidebar-tag-name" data-tags="ES6">
                <span class="iconfont-archer">&#xe606;</span>
                ES6
            </span>
        
            <span class="sidebar-tag-name" data-tags="GCC">
                <span class="iconfont-archer">&#xe606;</span>
                GCC
            </span>
        
            <span class="sidebar-tag-name" data-tags="Docker">
                <span class="iconfont-archer">&#xe606;</span>
                Docker
            </span>
        
            <span class="sidebar-tag-name" data-tags="CPP">
                <span class="iconfont-archer">&#xe606;</span>
                CPP
            </span>
        
            <span class="sidebar-tag-name" data-tags="gRPC">
                <span class="iconfont-archer">&#xe606;</span>
                gRPC
            </span>
        
            <span class="sidebar-tag-name" data-tags="ESLint">
                <span class="iconfont-archer">&#xe606;</span>
                ESLint
            </span>
        
            <span class="sidebar-tag-name" data-tags="Protobuf">
                <span class="iconfont-archer">&#xe606;</span>
                Protobuf
            </span>
        
            <span class="sidebar-tag-name" data-tags="机器学习">
                <span class="iconfont-archer">&#xe606;</span>
                机器学习
            </span>
        
            <span class="sidebar-tag-name" data-tags="PyTorch">
                <span class="iconfont-archer">&#xe606;</span>
                PyTorch
            </span>
        
            <span class="sidebar-tag-name" data-tags="Telegram">
                <span class="iconfont-archer">&#xe606;</span>
                Telegram
            </span>
        
            <span class="sidebar-tag-name" data-tags="Bot">
                <span class="iconfont-archer">&#xe606;</span>
                Bot
            </span>
        
            <span class="sidebar-tag-name" data-tags="Koa">
                <span class="iconfont-archer">&#xe606;</span>
                Koa
            </span>
        
            <span class="sidebar-tag-name" data-tags="Sequelize">
                <span class="iconfont-archer">&#xe606;</span>
                Sequelize
            </span>
        
            <span class="sidebar-tag-name" data-tags="Travis">
                <span class="iconfont-archer">&#xe606;</span>
                Travis
            </span>
        
            <span class="sidebar-tag-name" data-tags="MTProto">
                <span class="iconfont-archer">&#xe606;</span>
                MTProto
            </span>
        
            <span class="sidebar-tag-name" data-tags="Nginx">
                <span class="iconfont-archer">&#xe606;</span>
                Nginx
            </span>
        
            <span class="sidebar-tag-name" data-tags="Markdown">
                <span class="iconfont-archer">&#xe606;</span>
                Markdown
            </span>
        
            <span class="sidebar-tag-name" data-tags="Webpack">
                <span class="iconfont-archer">&#xe606;</span>
                Webpack
            </span>
        
    </div>
    <div class="iconfont-archer sidebar-tags-empty">&#xe678;</div>
    <div class="tag-load-fail" style="display: none; color: #ccc; font-size: 0.6rem;">
        缺失模块，请参考主题文档进行安装配置：https://github.com/fi3ework/hexo-theme-archer#%E5%AE%89%E8%A3%85%E4%B8%BB%E9%A2%98
    </div> 
    <div class="sidebar-tags-list"></div>
</div>

        <div class="sidebar-panel-categories">
    <div class="sidebar-categories-name">
    
        <span class="sidebar-category-name" data-categories="学习琐事">
            <span class="iconfont-archer">&#xe60a;</span>
            学习琐事
        </span>
    
        <span class="sidebar-category-name" data-categories="前端开发">
            <span class="iconfont-archer">&#xe60a;</span>
            前端开发
        </span>
    
        <span class="sidebar-category-name" data-categories="后端开发">
            <span class="iconfont-archer">&#xe60a;</span>
            后端开发
        </span>
    
        <span class="sidebar-category-name" data-categories="技术琐事">
            <span class="iconfont-archer">&#xe60a;</span>
            技术琐事
        </span>
    
    </div>
    <div class="iconfont-archer sidebar-categories-empty">&#xe678;</div>
    <div class="sidebar-categories-list"></div>
</div>

    </div>
</div>

        <!-- site-meta -->
        <script>
    var siteMetaRoot = "/"
    if (siteMetaRoot === "undefined") {
        siteMetaRoot = '/'
    }
    var siteMeta = {
        url: "https://LolipopJ.github.io",
        root: siteMetaRoot,
        author: "Lolipop"
    }
</script>

        <!-- import experimental options here -->
        <!-- Custom Font -->

    <!-- Check browser compatibility of CSS variables -->
    <script>
        if (browserSupportCSSVariables === undefined) {
            var browserSupportCSSVariables = window.CSS && window.CSS.supports && window.CSS.supports('--a', 0);
        }
    </script>
    <script>
        if (browserSupportCSSVariables) {
            var customFontName = 'Noto Sans SC:n3,n4,n5,n7'
            var customFontUrl = 'https://fonts.googleapis.cnpmjs.org/css2?family=Noto+Sans+SC:wght@300;400;500;700&amp;display=swap'
            if (!customFontName) {
                console.log('Custom font name is not set or read failed');
            }
            if (!customFontUrl) {
                console.log('Custom font url is not set or read failed');
            }
        } else {
            console.error('Current browser doesn\'t support custom font.')
        }
    </script>
    <script src="/scripts/customFontLoader.js?v=20211217" defer></script>


        <!-- main func -->
        <script src="/scripts/main.js?v=20211217"></script>
        <!-- dark mode -->
        <script src="/scripts/dark.js?v=20211217"></script>
        <!-- fancybox -->
        <script src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.js" defer></script>
        <!-- algolia -->
        
            <div class="site-search site-search-loading">
    <div class="algolia-popup popup">
        <div class="algolia-search">
            <div class="algolia-search-input-icon">
                <i class="fa fa-search"></i>
            </div>
            <div class="algolia-search-input" id="algolia-search-input"></div>
            <div class="popup-btn-close">
                <i class="iconfont-archer">&#xe609;</i>
            </div>
        </div>

        <div class="algolia-results">
            <div id="algolia-stats" class="algolia-stats"></div>
            <div id="algolia-hits"></div>
            <div id="algolia-pagination" class="algolia-pagination"></div>
        </div>
    </div>
</div>

            <script src="/scripts/search.js?v=20211217" defer></script>
        
        <!-- busuanzi -->
        
            <script src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" async></script>
        
        <!-- CNZZ -->
        
        <!-- async load share.js -->
        
            <script src="/scripts/share.js?v=20211217" async></script>
        
        <!-- mermaid -->
        
    </body>
</html>
